home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C08 / Volatile.cpp < prev   
Encoding:
C/C++ Source or Header  |  2000-05-25  |  942 b   |  42 lines

  1. //: C08:Volatile.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // The volatile keyword
  7.  
  8. class Comm {
  9.   const volatile unsigned char byte;
  10.   volatile unsigned char flag;
  11.   static const int bufsize = 100;
  12.   unsigned char buf[bufsize];
  13.   int index;
  14. public:
  15.   Comm();
  16.   void isr() volatile;
  17.   char read(int index) const;
  18. };
  19.  
  20. Comm::Comm() : index(0), byte(0), flag(0) {}
  21.  
  22. // Only a demo; won't actually work
  23. // as an interrupt service routine:
  24. void Comm::isr() volatile {
  25.   if(flag) flag = 0;
  26.   buf[index++] = byte;
  27.   // Wrap to beginning of buffer:
  28.   if(index >= bufsize) index = 0;
  29. }
  30.  
  31. char Comm::read(int index) const {
  32.   if(index < 0 || index >= bufsize)
  33.     return 0;
  34.   return buf[index];
  35. }
  36.  
  37. int main() {
  38.   volatile Comm Port;
  39.   Port.isr(); // OK
  40. //!  Port.read(0); // Error, read() not volatile
  41. } ///:~
  42.